//
//  ComicViewEps.swift
//  MovieAppDemo
//
//  Created by yanjin on 2025/2/12.
//

import SwiftUI
struct ComicViewEps: View {
    @Binding var item: MainPica
    @Binding var selectedTab:Int // 当前选中的标签
    @State private var tabWidth: CGFloat = 0 // 存储每个标签的宽度
    @StateObject private var viewModel = ComicDetailViewModel()
    @State private var hasAppeared = false
    @Binding var ep_id: Int
    @Binding var ep_name: String
    
    // eps_data 是章节列表数据，ep_id 是当前章节的 ID
    var eps_data: [ComicEps] {
        viewModel.detail?.eps ?? comiceps
    }
    
    // 获取当前章节的索引
    var currentChapterIndex: Int? {
        eps_data.firstIndex(where: { $0.id == ep_id })
    }
    
    private func updateEpName() {
        if let currentIndex = currentChapterIndex {
            ep_name = eps_data[currentIndex].name
        }
    }
    
    var body: some View {
        VStack(spacing: 0) {
            topProgressBar
            mainContent
        }
        .ignoresSafeArea(.all)
    }
    
    // 顶部进度条
    private var topProgressBar: some View {
        VStack {
            RoundedRectangle(cornerRadius: 10.0)
                .foregroundStyle(.gray)
                .frame(width: 50.0, height: 5.0)
        }
        .padding()
        .frame(height: 25.0, alignment: .top)
        .frame(maxWidth: .infinity)
        .background(Color("BgColor1"))
        .clipShape(RoundedRectangle(cornerRadius: 50.0))
    }
    
    // 主要内容区域
    private var mainContent: some View {
        VStack {
            headerSection
            tabSection
            contentSection
        }
        .padding(10)
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
        .background(Color("BgColor1"))
        .onChange(of: ep_id) { oldValue, newValue in
            updateEpName()
        }
        .onAppear {
            if !hasAppeared {
                viewModel.get_detail(main_id: item.id)
                hasAppeared = true
            }
        }
    }
    
    // 头部区域（封面 + 标题）
    private var headerSection: some View {
        HStack {
            CachedImageView(imageURL: item.cover)
                .scaledToFill()
                .frame(width: 60.0, height: .infinity)
                .clipped()
                .clipShape(RoundedRectangle(cornerRadius: 5))
                .lineLimit(1)
            
            VStack(alignment: .leading) {
                Text(item.name)
                    .foregroundColor(.white)
                    .font(.system(size: 16, weight: .medium))
                Text("已完结·共\(item.longs)话")
                    .foregroundColor(.white).opacity(0.8)
                    .font(.system(size: 14, weight: .medium))
                    .padding(.top, 2)
                Text("当前阅读·\(ep_name)")
                    .foregroundColor(.white).opacity(0.8)
                    .font(.system(size: 14, weight: .medium))
                    .padding(.top, 2)
            }
            Spacer()
        }
        .frame(height: 80.0)
    }
    
    // 标签切换区域
    private var tabSection: some View {
        VStack {
            HStack {
                Button(action: {
                    withAnimation {
                        selectedTab = 2
                    }
                    DispatchQueue.main.async {
                        selectedTab = 1
                    }
                }) {
                    Text("详情")
                        .font(.system(size: selectedTab == 1 ? 18 : 16))
                        .foregroundColor(selectedTab == 1 ? .white : .gray)
                }

                Button(action: {
                    withAnimation {
                        selectedTab = 1
                    }
                    DispatchQueue.main.async {
                        selectedTab = 2
                    }
                }) {
                    Text("目录")
                        .font(.system(size: selectedTab == 2 ? 18 : 16))
                        .foregroundColor(selectedTab == 2 ? .white : .gray)
                        .padding(.leading, 5)
                }
                Spacer()
            }
            .padding(.top)
            
            // 滑动横条
            Rectangle()
                .frame(width: 30.0, height: 3.0)
                .foregroundColor(.white)
                .cornerRadius(1.5)
                .offset(x: selectedTab == 1 ? -170 : -125)
                .animation(.easeInOut(duration: 0.3), value: selectedTab)
                .padding(.top, 5)
            
            Rectangle()
                .frame(maxWidth: .infinity, maxHeight: 1)
                .foregroundColor(.gray).opacity(0.2)
                .offset(y: -8)
        }
    }
    
    // 内容区域
    private var contentSection: some View {
        TabView(selection: $selectedTab) {
            detailsView
                .tag(1)
            chaptersView
                .tag(2)
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    }
    
    // 详情视图
    private var detailsView: some View {
        ScrollView(.vertical) {
            VStack {
                statsHeader
                statsLabels
                descriptionSection
            }
        }
        .scrollIndicators(.hidden)
        .frame(height: .infinity)
    }
    
    // 统计信息头部
    private var statsHeader: some View {
        HStack {
            Text("9.4")
                .font(.system(size: 24, weight: .medium))
                .frame(width: 50.0, alignment: .leading)
            
            Text("2.5w")
                .font(.system(size: 24, weight: .medium))
                .frame(width: 80.0, alignment: .leading)
                .padding(.leading, 40)
            
            Text("6.4w")
                .font(.system(size: 24, weight: .medium))
                .frame(width: 80.0, alignment: .leading)
                .padding(.leading, 40)
            Spacer()
        }
        .foregroundColor(.white)
        .padding(.top, 15)
    }
    
    // 统计信息标签
    private var statsLabels: some View {
        HStack {
            Text("评分")
                .font(.system(size: 14, weight: .medium))
                .frame(width: 50.0, alignment: .leading)
            
            Text("正在阅读")
                .font(.system(size: 14, weight: .medium))
                .frame(width: 80.0, alignment: .leading)
                .padding(.leading, 40)
            
            Text("加入收藏")
                .font(.system(size: 14, weight: .medium))
                .frame(width: 80.0, alignment: .leading)
                .padding(.leading, 40)
            Spacer()
        }
        .foregroundColor(.gray)
    }
    
    // 描述区域
    private var descriptionSection: some View {
        VStack {
            HStack {
                Text("简介")
                    .font(.system(size: 24, weight: .medium))
                    .foregroundColor(.white)
                ForEach(item.tags.prefix(4), id: \.self) { tag in
                    Text(tag)
                        .font(.system(size: 14))
                        .foregroundStyle(.gray)
                        .padding(6)
                        .background(Color.white.opacity(0.1))
                        .clipShape(RoundedRectangle(cornerRadius: 6))
                        .padding(.trailing, 2)
                }
                Spacer()
            }
            .padding(.top, 10)
            
            Text(item.desc)
                .frame(maxWidth: .infinity, alignment: .leading)
                .font(.system(size: 18, weight: .medium))
                .foregroundColor(.gray)
                .lineLimit(6)
                .padding(.top, 5)
        }
    }
    
    // 章节列表视图
    private var chaptersView: some View {
        ScrollView(.vertical) {
            LazyVStack(spacing: 20) {
                ForEach(eps_data, id: \.id) { item_eps in
                    let tag = (ep_id == item_eps.id) ? "正在阅读" : ""
                    ComicEpCard(item: item_eps, tag: tag, ep_id: $ep_id)
                        .onTapGesture {
                            ep_id = item_eps.id
                        }
                        .contentShape(Rectangle())
                }
            }
            .padding(.top, 15)
        }
    }
}


#Preview {
    @Previewable @State var item: MainPica = mainpicas[0]
    @Previewable @State var selectedTab:Int = 2 // 当前选中的标签
    @Previewable @State var ep_id: Int = 238721
    @Previewable @State var ep_name: String = "章节名称"
    ComicViewEps(item:$item, selectedTab:$selectedTab,ep_id: $ep_id,ep_name: $ep_name)
        .background(.black)
    
}
